#include <iostream>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

using namespace std;

#define FILENAME ".fifo"

int MakeFifo()
{
    int n = mkfifo(FILENAME, 0666);
    if (n < 0)
    {
        cerr << "error" << errno << " errno resaon " << strerror(errno) << endl;
        return 1;
    }
    std::cout << "创建管道文件成功" << std::endl;
    return 0;
}

int main()
{
Start:
    int fd = open(FILENAME, O_RDONLY);
    if (fd < 0)
    {
        if (MakeFifo() == 0)
            goto Start;
        else 
            return 2;
    }
    std::cout << "打开管道文件成功" << std::endl;


    std::cout << "服务端启动成功！！！ " << std::endl;

    char buffer[1024];
    while (true)
    {
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = '\0';
            cout << "cilent say: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "服务端退出成功" << endl;
            break;
        }
    }

    close(fd);
    std::cout << "关闭管道文件成功" << std::endl;

    return 0;
}